import axios from 'axios';
import { history } from 'umi';
import qs from 'qs';

if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = '/service';
} else {
  // @ts-ignore
  axios.defaults.baseURL = '后端地址';
}

const instance = axios.create({
  headers: {
    'x-requested-with': 'XMLHttpRequest',
    'Content-Type': 'application/json',
  },
  transformRequest: (data, header) => {
    const type = header['Content-Type'];
    if (type && type === 'application/json') {
      return JSON.stringify(data);
    }
    return qs.stringify(data);
  },
});

instance.interceptors.request.use((request) => {
  const token = window.localStorage.getItem('token');
  if (token) {
    request.headers = {
      ...request.headers,
      token: token,
    };
  }
  return request;
});

instance.interceptors.response.use(
  (response) => {
    if (!response.data.success && response.data.code === 'FAILURE') {
      return Promise.reject(response);
    } else if (
      !response.data.success &&
      response.data.code === 'UNAUTHORIZED'
    ) {
      history.replace('/401');
      return Promise.reject(response);
    }
    return response.data;
  },
  (error) => {
    if (error.response) {
      if (error.response.status === 401) {
        history.replace('/401');
      } else if (error.response.status === 403) {
        history.replace('/403');
      } else {
        history.replace('/500');
      }
      return Promise.reject(error.response);
    }
    history.replace('/500');
    return Promise.reject(error);
  },
);

export default instance;
